package com.uni.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/1/28 0:01
 **/

@Configuration
public class DruidConfig {
    //配置Druid监控管理后台的servlet
    //内置Servlet容器时没有web.xml文件，所以使用springboot的注册servlet的方式
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //这些参数可以在com.alibaba.druid.support.http.StatViewServlet的父类com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String,String> initParams = new HashMap<>();
        initParams.put("loginUsername","admin");//后台管理界面的登录账号
        initParams.put("loginPassword","123456");//后台管理界面的登录密码
        //限制访问后台的IP
        initParams.put("allow","127.0.0.1");//为空或者为null时，表示允许所有访问
        //deny:Druid后台黑名单
        initParams.put("dz","192.168.1.20");//表示禁止此ip访问
        //设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }
    //配置Druid监控的filter
    //webStatFiler:用于配置web和Druid数据源之间的管理关联监控统计
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //exclusions:设置哪些请求进行过滤排除掉，从而不进行统计
        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");
        //"/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}
